package com.highspeed.bdk.controller.physical.service;

import com.highspeed.bdk.TestMainApplication;
import com.highspeed.bdk.bean.entity.physical.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {TestMainApplication.class})
@Transactional
public class CpuServiceTester extends BaseDeviceServiceTester {
    private Cpu cpu1;
    private Cpu cpu2;

    @Before
    public void init() {
        PhysicalTopology pt = createPhysicalTopology();
        physicalTopologyService.saveAndFlush(pt);
        physicalTopologyService.clear();

        MachineBox mb = createMachineBox();
        mb.setPhysicalTopology(pt);
        machineBoxService.saveAndFlush(mb);
        machineBoxService.clear();

        Board board = createBoard();
        board.setMachineBox(mb);
        boardService.saveAndFlush(board);
        boardService.clear();


        Cpu cpu = createCpu();
        cpu.setBoard(board);
        this.cpu1 = cpuService.save(cpu);
        cpu = createCpu();
        cpu.setBoard(board);
        this.cpu2 = cpuService.save(cpu);

        createPhysicalLink(cpu1, cpu2);


        cpuService.flush();
        cpuService.clear();
    }

    @Test
    public void save() {
        Assert.assertNotNull(cpu1);
        Assert.assertNotNull(cpu2);

    }

    @Test(expected = JpaSystemException.class)
    public void saveException() {
        Cpu entity = createCpu();
        cpuService.saveAndFlush(entity);
    }

    @Test
    public void deleteLinks() {

        List<PhysicalLink> physicalLinks = physicalLinkService.all();
        List<PhysicalLink> mbLinks = physicalLinkService.findByCpuId(cpu1.getId());
        Assert.assertEquals(mbLinks.size(), 1);

        cpuService.delete(cpu1.getId());
        List<PhysicalLink> nowBbLinks = physicalLinkService.findByBoardId(cpu1.getId());
        Assert.assertEquals(nowBbLinks.size(), 0);

        Cpu tmp = cpuService.findOne(cpu1.getId());
        Assert.assertNull(tmp);
        List<PhysicalLink> nowLinks = physicalLinkService.all();
        Assert.assertEquals(physicalLinks.size() - mbLinks.size(), nowLinks.size());
    }

    @Test
    public void deleteCpus() {
        cpuService.delete(cpu1.getId());
        Cpu cpu = cpuService.findOne(cpu1.getId());
        Assert.assertNull(cpu);
    }

}
